package com.yuanfeng.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.dto.order.ConsumeRecordByBusinessDTO;
import com.yuanfeng.commoms.dto.order.ConsumeRecordParaDTO;
import com.yuanfeng.commoms.dto.order.ConsumeTradeParaDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.vo.base.DealerApplyInfoVO;
import com.yuanfeng.commoms.vo.goods.WapGoodsSaleSumUpdateVO;
import com.yuanfeng.commoms.vo.order.*;
import com.yuanfeng.commoms.vo.shop.ShippingListVO;
import com.yuanfeng.commoms.vo.shop.ShopParaVO;
import com.yuanfeng.commoms.vo.shop.ShopUserMessageResultVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.order.feign.BusinessServiceClient;
import com.yuanfeng.order.feign.GoodServiceClient;
import com.yuanfeng.order.feign.PayMentServiceClient;
import com.yuanfeng.order.mapper.*;
import com.yuanfeng.order.service.OrderSupplierCreateServer;
import com.yuanfeng.order.vo.DealerShopInfoVO;
import com.yuanfeng.order.vo.OrderInfoVO;
import com.yuanfeng.order.vo.SupplyOrderPriceVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @ClassName OrderSupplierCreateServerImpl
 * @Description 供应商 创建订单 计算价格
 * @Author cyp
 * @Date 2023/7/14 15:24
 * @Version 1.0
 */
@Service
public class OrderSupplierCreateServerImpl implements OrderSupplierCreateServer {
    @Autowired
    private BusinessServiceClient businessServiceClient;

    @Autowired
    private OrderSupplierCreateMapper orderSupplierCreateMapper;

    @Autowired
    private OrderInvoiceInfoMapper orderInvoiceInfoMapper;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private OrderBaseMapper orderBaseMapper;

    @Autowired
    private PayMentServiceClient payMentServiceClient;

    @Autowired
    private GoodServiceClient goodServiceClient;

    @Autowired
    private OrderUserCartMapper orderUserCartMapper;


    private final static Logger log = LoggerFactory.getLogger(OrderSupplierCreateServerImpl.class);

    @Override
    public ResponseResult calculatePrice(String message) {
        // 1.校验计算运费
        CommonParameterVO commonParam = JSON.parseObject(message, CommonParameterVO.class);
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(commonParam.getToken());
        ResponseResult resultResp = this.goodsShipping(message);
        if (resultResp.getCode() != (CommonStatusEnum.SUCCESS.getCode())) {
            return resultResp;
        }
        // 2.获取商品
        String goodsDetails = resultResp.getData().toString();
        // json转对象
        List<WapShopShippingQueryResultVO> wapList = JSON.parseObject(goodsDetails, new TypeReference<List<WapShopShippingQueryResultVO>>() {});
        // 3.计算订单价格
        SupplyOrderPriceVO supplyOrderPrice = new SupplyOrderPriceVO();
        // 3.1 获取所有供应商店铺的店铺折扣
        Map<Integer, DealerApplyInfoVO> dealerApplyInfoMap = new HashMap<>(8);
        List<Integer> supplyShopIdList = wapList.stream().map(WapShopShippingQueryResultVO::getShopId).collect(Collectors.toList());
        DealerShopInfoVO dealerShopInfo = new DealerShopInfoVO(userInfo.getShopId(),supplyShopIdList);
        List<DealerApplyInfoVO> dealerApplyInfoList =  orderSupplierCreateMapper.queryDealerApplyListByShop(dealerShopInfo.getDealerShopId(),dealerShopInfo.getSupplyShopIdList());
        if(null != dealerApplyInfoList && dealerApplyInfoList.size() > 0 ){
            dealerApplyInfoMap = dealerApplyInfoList.stream().collect(Collectors.toMap(DealerApplyInfoVO::getSupplierShopId, Function.identity()));
        }
        // 店铺发票信息
        List<StoreInformationVO> storeInformationList = commonParam.getStoreInformationList();
        Map<Integer,StoreInformationVO> storeInformationMap = storeInformationList.stream().collect(Collectors.toMap(StoreInformationVO::getShopId,Function.identity()));

        List<ShippingListVO> shippingList = new ArrayList<>();
        ShopParaVO sp = new ShopParaVO();
        // 根据店铺循环
        for (WapShopShippingQueryResultVO shopShippingQueryResult : wapList) {
            // 当前店铺优惠比例
            BigDecimal discount = BigDecimal.ZERO;
            if(null != dealerApplyInfoMap.get(shopShippingQueryResult.getShopId())){
                discount = new BigDecimal(dealerApplyInfoMap.get(shopShippingQueryResult.getShopId()).getDealerDiscount()).divide(new BigDecimal(100)).setScale(2, BigDecimal.ROUND_UP);
            }
            List<WapShippingQueryResultVO> goodsBaseList = new ArrayList<>();

            // 存放shopId&&每家店铺运费
            ShippingListVO sl = new ShippingListVO();
            sl.setShopId(shopShippingQueryResult.getShopId());
            sl.setShopName(shopShippingQueryResult.getShopName());
            sl.setInvoiceId(storeInformationMap.get(shopShippingQueryResult.getShopId()).getInvoiceId());
            sl.setBuyerMessage(shopShippingQueryResult.getBuyerMessage());
            sl.setDistrictId(shopShippingQueryResult.getDistrictId());
            sl.setShopDistributorId(shopShippingQueryResult.getShopId());
            sl.setShopSelfSupport(shopShippingQueryResult.getShopSelfSupport());
            // 店铺默认发货时长 72 小时
            BigDecimal receivingTime = new BigDecimal(72);
            sl.setReceivingTime(receivingTime);

            // 每家店铺总价格(不含运费与优惠价格)
            BigDecimal shopGoodsTotalPrice = new BigDecimal(0);
            // 店铺总折扣
            BigDecimal shopGoodsTotalDiscount = BigDecimal.ZERO;
            // 商品数量
            Integer goodsNo = 0;
            // 获取商品计算商品价格
            for (WapShopShippingResultVO shopShippingResult : shopShippingQueryResult.getGoodsBaseList()) {
                List<WapShippingQueryResultVO> wsqrList = shopShippingResult.getGoodsBaseList();
                for (WapShippingQueryResultVO shippingQueryResult : wsqrList) {
                    // 限购校验
                    resultResp = this.goodsSaleCheck(shippingQueryResult,userInfo);
                    // 付款价格(不包含运费)
                    BigDecimal price = shippingQueryResult.getGoodsPrice().multiply(new BigDecimal(shippingQueryResult.getGoodsNum()));
                    shippingQueryResult.setGoodsPaymentPrice(price);
                    // 商品优惠金额
                    shippingQueryResult.setGoodsDisountPrice(price.multiply(discount).setScale(2,BigDecimal.ROUND_HALF_UP));
                    goodsNo = goodsNo + shippingQueryResult.getGoodsNum();
                    shopGoodsTotalPrice = shopGoodsTotalPrice.add(price);
                    shopGoodsTotalDiscount = shopGoodsTotalDiscount.add(shippingQueryResult.getGoodsDisountPrice());
                }
                goodsBaseList.addAll(wsqrList);
            }
            sl.setDistributionDiscount(discount.multiply(new BigDecimal(100).setScale(2, RoundingMode.HALF_UP)));
            sl.setWsqrList(goodsBaseList);

            sl.setGoodsNo(goodsNo);
            // 店铺运费
            sl.setShipping(shopShippingQueryResult.getShippingFee());
            // 店铺商品总金额
            sl.setShopPrice(shopGoodsTotalPrice);
            // 店铺折扣
            sl.setShopDiscount(shopGoodsTotalDiscount);
            // 店铺订单总金额
            sl.setShopTotalPrice(shopGoodsTotalPrice.add(shopShippingQueryResult.getShippingFee()));
            shippingList.add(sl);

            supplyOrderPrice.setTotalShippingPrice(shopShippingQueryResult.getShippingFee());
            supplyOrderPrice.setGoodsTotalPrice(shopGoodsTotalPrice);
            supplyOrderPrice.setTotalDisountPrice(sl.getShopDiscount());
        }
        sp.setShippingList(shippingList);
        // 订单总金额
        sp.setTotalPrice(supplyOrderPrice.getOrderPaymentPrice());
        // 总运费
        sp.setTotalShipping(supplyOrderPrice.getTotalShippingPrice());
        // 总折扣
        sp.setShopTotalDiscount(supplyOrderPrice.getTotalDisountPrice());
        sp.setOrderDiscountType(0);
        // 商品总金额
        sp.setAllShopTotalPrice(supplyOrderPrice.getGoodsTotalPrice());

        if(resultResp.getCode() == CommonStatusEnum.SUCCESS.getCode()){
            resultResp.setData(sp);
            return resultResp;
        }

        if (supplyOrderPrice.getOrderPaymentPrice().compareTo(BigDecimal.ZERO) <= 0) {
            resultResp.setData(sp);
            resultResp.setMessage(BizCodeEnume.SYSTEM_ERROR.getMsg());
            resultResp.setCode(BizCodeEnume.SYSTEM_ERROR.getCode());
            return resultResp;
        }
        return ResponseResult.success(sp);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult createOrders(String para, HttpServletRequest request) {
        try {
            ResponseResult resultResp;
            List<String> orderList = new ArrayList<>();
            CommonParameterVO cp = JSON.parseObject(para, new TypeReference<CommonParameterVO>() {
            });

            //判断库存
            ResponseResult goodsStockresult = verifyGoodsStock(cp);
            if (goodsStockresult.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
                return goodsStockresult;
            }
            String liveId = request.getHeader("liveId");
            String accountId = request.getHeader("accountId");
            UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(cp.getToken());
            // 收货人姓名
            String orderReceiverName = cp.getOrderReceiverName();
            // 收货人地址
            String orderReceiverAddress = cp.getOrderReceiverAddress();
            // 收货人联系方式
            String orderReceiverContact = cp.getOrderReceiverContact();
            // 收货人省Id
            Integer orderReceiverProvinceId = cp.getOrderReceiverProvinceId();
            // 收货人市Id
            Integer orderReceiverCityId = cp.getOrderReceiverCityId();
            // 收货人区Id
            Integer orderReceiverAreaId = cp.getOrderReceiverAreaId();
            String zbName = "";
            List<StoreInformationVO> storeInformationList = cp.getStoreInformationList();
            Map<String,InvoiceEntityInfoVO> invoiceInfoMap = new HashMap<>();
            for(StoreInformationVO si:storeInformationList){
                String shopIdTmp = si.getShopId()+"";
                InvoiceEntityInfoVO ieiTmp = si.getInvoiceInfo();
                invoiceInfoMap.put(shopIdTmp,ieiTmp);
            }
            // 获取计算价格
            resultResp = this.calculatePrice(para);
            if (resultResp.getCode() != 1) {
                return resultResp;
            }
            ShopParaVO shopPara = JSON.parseObject(JSON.toJSONString(resultResp.getData()), ShopParaVO.class);

            // 存放ConsumeTrade参数
            ConsumeTradeParaDTO ctp = new ConsumeTradeParaDTO();
            // 存放ConsumeRecord参数
            ConsumeRecordParaDTO crp = new ConsumeRecordParaDTO();
            // 存放卖家信息
            ConsumeRecordByBusinessDTO crb = new ConsumeRecordByBusinessDTO();
            BigDecimal orderGoodsCommission = new BigDecimal(0);//平台佣金
            BigDecimal orderBaseCommission =new BigDecimal(0);//平台佣金
            BigDecimal goodsMemberDiscount = new BigDecimal(0);//会员折扣  供应商暂不涉及会员折扣直接赋值为0
            BigDecimal baseMemberDiscount =new BigDecimal(0);//会员折扣
            String orderDate = DateUtils.getYear() + "-" + DateUtils.getMonth() + "-" + DateUtils.getDay();
            List<Integer> goodsIdList;
            String invoiceName = null;// 发票信息
            // 商户订单号
            String paymentNumber = "U" + DateUtils.getTimeStamp() + DateUtils.randomLengthByTwo();
            for (ShippingListVO shippingList : shopPara.getShippingList()) {
                // 保存商品销售数量信息列表
                List<WapGoodsSaleSumUpdateVO> goodsSaleInfoList = new ArrayList<>();
                // 订单编号
                String orderId;
                if (userInfo.getUserId().length() <= 8) {
                    orderId = DateUtils.nowtime() + userInfo.getUserId() + DateUtils.randomLengthByTwo();
                } else {
                    String oldUserId = userInfo.getUserId().toString();
                    String newUserId = oldUserId.substring(0, 4) + oldUserId.substring(oldUserId.length() - 4);
                    orderId = DateUtils.nowtime() + newUserId + DateUtils.randomLengthByTwo();
                }
                //此处增加新开票功能
                String invoiceKey = shippingList.getShopId()+"";
                InvoiceEntityInfoVO invoiceInfo = invoiceInfoMap.get(invoiceKey);
                if(null != invoiceInfo){
                    invoiceInfo.setOrderId(orderId);
                    invoiceInfo.setUserId(userInfo.getUserId());
                    invoiceInfo.setInvoiceStatus(1);
                    orderInvoiceInfoMapper.addInvoiceInfo(invoiceInfo);
                }
                List<String> goodsNameList = new ArrayList<>();
                for (WapShippingQueryResultVO goodsBase : shippingList.getWsqrList()) {
                    BigDecimal orderGoodsPaymentAmount = goodsBase.getGoodsPaymentPrice().add(goodsBase.getGoodsShippingFee()).subtract(goodsBase.getGoodsDisountPrice());
                    //计算平台抽佣
                    if(null != goodsBase.getCatId()){
                        BigDecimal catCommission = orderGoodsMapper.queryCatCommission(goodsBase.getCatId());//查询分类抽佣比例
                        if(null == catCommission){
                            catCommission = new BigDecimal(0);
                        }
                        catCommission = catCommission.divide(new BigDecimal(100),2, RoundingMode.HALF_UP).setScale(2, RoundingMode.HALF_UP);//计算平台抽佣
                        orderGoodsCommission = orderGoodsPaymentAmount.subtract(goodsBase.getGoodsShippingFee()).multiply(catCommission).setScale(2, RoundingMode.HALF_UP);
                        orderBaseCommission = orderBaseCommission.add(orderGoodsCommission).setScale(2, RoundingMode.HALF_UP);
                    }

                    orderGoodsMapper.insertSupplierByOrderGoods(orderId, shippingList.getShopId(),
                            shippingList.getShopName(), goodsBase.getGoodsId(), goodsBase.getCommonId(), userInfo.getUserId(),
                            goodsBase.getGoodsName(), goodsBase.getCatId(), goodsBase.getGoodsSpec(), goodsBase.getGoodsPrice(), goodsBase.getGoodsNum(),
                            goodsBase.getGoodsImage(), goodsBase.getGoodsShippingFee(), goodsBase.getGoodsPaymentPrice(), BigDecimal.ZERO,
                            orderGoodsPaymentAmount, 1, 0, BigDecimal.ZERO,
                            BigDecimal.ZERO, BigDecimal.ZERO, 0, 0,
                            DateUtils.getNowDateToString(), 0, 0, 0,0,BigDecimal.ZERO,BigDecimal.ZERO,orderGoodsCommission,goodsMemberDiscount);

                    // 保存商品销量信息
                    WapGoodsSaleSumUpdateVO goodsSaleInfo = this.saveGoodsSale(goodsBase, cp.getToken(), cp.getTreasureOrderShopId());
                    goodsSaleInfoList.add(goodsSaleInfo);
                    goodsNameList.add(goodsBase.getGoodsName());
                }
                // 添加订单
                ShopUserMessageResultVO shopUserMessageResult = orderSupplierCreateMapper.queryUserId(shippingList.getShopId());
                BigDecimal orderpay = shippingList.getShopTotalPrice().subtract(shippingList.getShopDiscount());//订单金额
                orderBaseMapper.insertSupplierByOrderBase(orderId, shippingList.getShopId(),null, shippingList.getShopName(),
                        userInfo.getUserId(), userInfo.getUserName(), shopUserMessageResult.getUserId(), shopUserMessageResult.getUserName(), orderDate, DateUtils.getNowDateToString(), orderReceiverName,
                        orderReceiverAddress, orderReceiverContact, orderReceiverProvinceId, orderReceiverCityId,
                        orderReceiverAreaId, paymentNumber, invoiceName, shippingList.getInvoiceId(), shippingList.getShopPrice(),
                        orderpay, shippingList.getShopDiscount(), shippingList.getShipping(), 0,
                        shippingList.getBuyerMessage(), 1, 0, BigDecimal.ZERO, null, cp.getPlatForm(),
                        null, BigDecimal.ZERO, BigDecimal.ZERO, null, BigDecimal.ZERO,
                        BigDecimal.ZERO, shippingList.getDistrictId(), null == userInfo.getUserParentShopId() ? 0 : userInfo.getUserParentShopId(), userInfo.getInviteSubsiteId(), cp.getTreasureOrderShopId(),
                        0, 0, null, 0, liveId, accountId, 1, null, null,
                        shippingList.getShopDistributorId(), CommonType.orderType.SUPPLY_TYPE.getCode(),shippingList.getShopId(),shippingList.getShopName(),
                        BigDecimal.ZERO,0,1,null,2,2,BigDecimal.ZERO,BigDecimal.ZERO,orderBaseCommission,baseMemberDiscount,shippingList.getShopDiscount());

                Integer count = orderBaseMapper.checkInvoiceSwitchStatus(shippingList.getShopId());
                if(count>0){
                    if(!orderList.contains(orderId)) {
                        orderList.add(orderId);
                    }
                }
                // consumeRecord所需参数(商家订单)
                crb.setSellId(shopUserMessageResult.getUserId());
                // 订单号
                crb.setOrderId(orderId);
                crb.setUserName(shopUserMessageResult.getUserName());
                // 支付号
                crb.setPaymentNumber(paymentNumber);
                crb.setTotalPrice(shippingList.getShopTotalPrice());
                // 存放goodsnameConsumeRecord
                crb.setGoodsName(goodsNameList);
                payMentServiceClient.insertConsumeRecordByBusiness(crb);
                // fegin调用插入数据ConsumeRecord(买家订单)
                crp.setUserId(userInfo.getUserId());
                // 订单号
                crp.setOrderId(orderId);
                crp.setUserName(userInfo.getUserName());
                // 支付号
                crp.setPaymentNumber(paymentNumber);
                crp.setTotalPrice(shippingList.getShopTotalPrice());
                // 存放goodsnameConsumeRecord
                crp.setGoodsName(goodsNameList);
                payMentServiceClient.insertConsumeRecord(crp);
                // consumeTrade所需参数
                ctp.setUserId(userInfo.getUserId());
                // 订单号
                ctp.setOrderId(orderId);
                ctp.setSellerId(shopUserMessageResult.getUserId());
                // 支付号
                ctp.setPaymentNumber(paymentNumber);
                // 商品价格
                ctp.setTotalPrice(shippingList.getShopTotalPrice());
                // 优惠价格
                ctp.setTradeDiscount(shippingList.getShopDiscount());
                ctp.setGoodsName(goodsNameList);
                // fegin调用插入数据ConsumeTrade
                payMentServiceClient.insertConsumeTrade(ctp);
                //更新库存
                Map<String,String> param = new HashMap<>();
                param.put("saleSum",JSON.toJSONString(goodsSaleInfoList));
                goodServiceClient.updateSaleSum(param);

                RedisUtil.set(YFConfig.YF_SALENUM + paymentNumber, JSON.toJSONString(goodsSaleInfoList), 86400);
                RedisUtil.set(YFConfig.YF_SALENUM + orderId, JSON.toJSONString(goodsSaleInfoList), 86400);
                RedisUtil.set(YFConfig.YF_SHOP_IS_SUPPORT + orderId, shippingList.getShopSelfSupport().toString(), 86400);
                // 存放付款金额
                RedisUtil.set(YFConfig.YF_USERAMOUNTACTUALLYPAID + "--" + cp.getToken() + "--" + userInfo.getUserId(), shopPara.getTotalPrice().toString(), 1200);
                // 保存商家电话信息，在支付完成后发送发货提醒会用到
                RedisUtil.set(YFConfig.YF_SELLERPHONE + "--" + orderId, shopUserMessageResult.getContactsPhone(), 86400);

                // 下单成功，删除商品
                goodsIdList = shippingList.getWsqrList().stream().map(WapShippingQueryResultVO::getGoodsId).collect(Collectors.toList());
                orderUserCartMapper.batchDeleteGoods(userInfo.getUserId(), goodsIdList);
            }
            OrderInfoVO info = new OrderInfoVO();
            info.setPaymentNumber(paymentNumber);
            info.setOrderIdList(orderList);
            return ResponseResult.success(info);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(0, "下单失败");
        }
    }
    /**
     * 计算商品运费信息并校验
     * @param message
     * @return
     */
    private ResponseResult goodsShipping(String message) {
        ResponseResult rr = businessServiceClient.queryShipping(message);;
        if (rr.getCode() == (CommonStatusEnum.SUCCESS.getCode())) {
            return rr;
        } else {
            if (rr.getCode() == (BizCodeEnume.PRODUCTS_OUT_OF_STOCK_IN_THIS_SALES_AREA.getCode())) {
                return ResponseResult.fail(BizCodeEnume.PRODUCTS_OUT_OF_STOCK_IN_THIS_SALES_AREA.getMsg());
            } else {
                return ResponseResult.fail(BizCodeEnume.NO_INFORMATION_OBTAINED.getMsg());
            }
        }
    }
    /**
     * 商品限购校验
     * @param shippingQueryResult
     * @param userInfo
     * @return
     */
    private  ResponseResult goodsSaleCheck(WapShippingQueryResultVO shippingQueryResult,UserInfoVO userInfo){
        Integer goodsMaxSale = shippingQueryResult.getGoodsMaxSale();
        Integer goodsStock = shippingQueryResult.getGoodsStock();
        Integer goodsNumber = shippingQueryResult.getGoodsNum();
        // 商品限购判断
        if (shippingQueryResult.getGoodsMaxSale().intValue() != 0) {
            // 判断商品是否有最大限购数量
            if (goodsNumber > goodsMaxSale || goodsNumber > goodsStock) {
                return ResponseResult.fail(0, "您购买的"+shippingQueryResult.getGoodsName()+ BizCodeEnume.GOODS_EXCEEDS_THE_MAXIMUM_PURCHASE_LIMIT.getMsg());
            }
        } else {
            // 商品无最大限购数量时，以商品库存为基准进行判断
            goodsMaxSale = goodsStock;
            if (goodsNumber > goodsMaxSale || goodsNumber > goodsStock) {
                return ResponseResult.fail(0, "您购买的"+shippingQueryResult.getGoodsName()+ BizCodeEnume.GOODS_EXCEEDS_THE_MAXIMUM_PURCHASE_LIMIT.getMsg());
            }
        }
        if (shippingQueryResult.getCommonLimit().intValue() == 1) {
            // 判断是否是限购商品
            //限购次数
            Integer restrictionTimes = shippingQueryResult.getRestrictionTimes();
            //限购时间
            Integer restrictionHours = shippingQueryResult.getRestrictionHours();
            //下单数量
            Integer purchasingGoods = orderSupplierCreateMapper.queryPurchasingGoods(userInfo.getUserId(), shippingQueryResult.getGoodsId(), restrictionHours);
            Integer purchasingGoodsStatusNum = orderSupplierCreateMapper.queryPurchasingGoodsStatusNum(userInfo.getUserId(),shippingQueryResult.getGoodsId());
            if (restrictionTimes == (purchasingGoods + purchasingGoodsStatusNum)) {
                return  ResponseResult.fail(0, "您购买的"+shippingQueryResult.getGoodsName()+"商品规定" + restrictionHours + "天之内只能下单" + restrictionTimes + "次，请勿购买！");
            }
        }
        return ResponseResult.success();
    }
    /**
     * 保存商品销售数据
     * @param goodsBase
     * @param token
     * @param treasureOrderShopId
     * @return
     */
    private WapGoodsSaleSumUpdateVO saveGoodsSale(WapShippingQueryResultVO goodsBase,String token,Integer treasureOrderShopId){
        // 存放商品信息，增加销量
        WapGoodsSaleSumUpdateVO wssu = new WapGoodsSaleSumUpdateVO();
        Integer goodsType = 0;
        // 聚宝订单
        if (goodsBase.getCommonIsTreasure().equals(1)) {
            goodsType = 1;
        }
        wssu.setToken(token);
        wssu.setGoodsId(goodsBase.getGoodsId());
        wssu.setGoodsNum(goodsBase.getGoodsNum());
        wssu.setCommonId(goodsBase.getCommonId());
        wssu.setGoodsType(goodsType);
        wssu.setTreasureOrderShopId(treasureOrderShopId);
        return wssu;
    }


    public ResponseResult verifyGoodsStock(CommonParameterVO cp) {
        if (cp.getIsInquiry() == null || cp.getIsInquiry() != 1) {
            for (StoreInformationVO str1 : cp.getStoreInformationList()) {
                List<GoodsInformationVO> goodsList = str1.getGoodsBaseList();
                for (GoodsInformationVO str2 : goodsList) {
                    Map<String, Object> resmap = orderBaseMapper.queryBygoodsId(str2.getGoodsId());
                    if (null != resmap) {
                        //库存
                        Integer goodsStock = Integer.parseInt(resmap.get("goodsStock").toString());
                        log.info("stock库存=================>{}", goodsStock);
                        if (str2.getGoodsNum() > goodsStock) {
                            //部分商品购买数量超过库存数量
                            return ResponseResult.fail(BizCodeEnume.EXCEEDING_INVENTORY_QUANTITY);
                        }
                    }
                }
            }
        }
        return ResponseResult.success();
    }
}
